-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unsorted Graph implementation using Adjacency Matrix.cpp
89 lines (86 loc) · 2.77 KB
/
Unsorted Graph implementation using Adjacency Matrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Graph {
private:
int m = 0, aID = -1, bID = -1; bool directed;
vector<vector<int>> matrix;
vector<int> OL, NL; // Old List, New List
int searchIndex(vector<int> vect, int key){
for(int i = 0; i < vect.size(); i++)
if(vect[i] == key) return i;
return -1;
}
void add_to_list(int u, int v){
NL.push_back(u);
NL.push_back(v);
sort(NL.begin(), NL.end());
NL.erase(unique(NL.begin(), NL.end()), NL.end());
aID = searchIndex(NL, u);
bID = searchIndex(NL, v);
}
void shift(int from, int to = 0, string test = ""){
if(to < from) to = matrix.size()-1;
vector<int> swapRow; int swapK;
for(int row = matrix.size()-1; row >= 0; --row){
if(row >= from && row <= to){
if(row == to) swapRow = matrix[row];
matrix[row] = (row == from) ? swapRow : matrix[row-1];
}
swapK = matrix[row][to];
move(matrix[row].begin()+from, matrix[row].begin()+to, matrix[row].begin()+from+1);
matrix[row][from] = swapK;
}
}
void resizeMatrix(int from, int to, string test = ""){
if(OL.size() > from && from != NL.size()-1 && OL[from] != NL[from]){
shift(from, to);
}
if(from != to){
if(OL.size() > to && to != NL.size()-1 && OL[to] != NL[to]){
shift(to, from, test);
}
}
}
public:
Graph(int nodes, bool directedGraph = false){ // Constructor
m = nodes;
directed = directedGraph;
matrix = vector<vector<int>>(m, vector<int>(m));
}
void addEdge(int u, int v, string test = ""){
add_to_list(u, v);
if(NL.size() > m){
cout << "Invalid edge [" << u << "]" << (directed ? "" : "🠨") << "🠪[" << v << "]" << endl << "Node value should be max (m-1)" << endl << endl;
NL = OL;
} else {
resizeMatrix(aID, bID, test);
matrix[aID][bID] = 1;
if(!directed && aID != bID) matrix[bID][aID] = 1;
OL = NL; // Update Old List (OL) from the new New List (NL)
}
}
void print(){
for (int row = 0; row < matrix.size(); row++){
for (int col = 0; col < matrix[row].size(); col++){
cout << " " << matrix[row][col];
}
cout << endl;
}
}
};
int main(){
int m = 6; bool directed = false;
Graph G(m, directed);
G.addEdge(10, 12);
G.addEdge(10, 14);
G.addEdge(11, 10);
G.addEdge(12, 13);
G.addEdge(12, 15);
G.addEdge(13, 14);
G.addEdge(14, 15);
G.addEdge(14, 11);
cout << "Adjacency Matrix: " << endl;
G.print();
}